
//
//  MeTableViewController.m
//  Mango
//
//  Created by lanou3g on 16/5/12.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "MeTableViewController.h"
#import <SVProgressHUD.h>
#import "EditUserInfoViewController.h"
#import "XJUserInfoManager.h"
#import "LoginViewController.h"
#import "SelectedTableViewController.h"
#import "DBManager.h"
@interface MeTableViewController ()
@property (nonatomic, copy) NSString *userName;
@property (nonatomic, weak) UISwitch *changeSkinSwitch;
@property (nonatomic, weak) UISwitch *shakeCanChangeSkinSwitch;
@property (nonatomic, weak) UISwitch *imageDownLoadModeSwitch;
@property (nonatomic, assign) CGFloat cacheSize;
@property (nonatomic, copy) NSString *currentSkinModel;
@end

CGFloat const footViewHeight = 30;

@implementation MeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.contentInset = UIEdgeInsetsMake(CGRectGetMaxY(self.navigationController.navigationBar.frame) + 30, 0, 0, 0);
//    NSLog(@"%@",NSHomeDirectory());
}


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkinModel) name:SkinModelDidChangedNotification object:nil];
    [self caculateCacheSize];
    [self updateSkinModel];
}


-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


-(void)caculateCacheSize {
    float imageCache = [[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.sqlite"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float sqliteCache = [fileManager attributesOfItemAtPath:path error:nil].fileSize/1024.0/1024.0;
    self.cacheSize = imageCache + sqliteCache;
}

#pragma mark 更新皮肤模式 接到模式切换的通知后会调用此方法
-(void)updateSkinModel {
    self.currentSkinModel = [[NSUserDefaults standardUserDefaults] stringForKey:CurrentSkinModelKey];
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {
        self.tableView.backgroundColor = [UIColor blackColor];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    } else {//日间模式
        self.tableView.backgroundColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1.0];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }
    [self.tableView reloadData];
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) return 1;
    else if(section == 1) return 2;
    return 2;
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return footViewHeight;
}

#pragma mark -UITableViewDataSource 返回indexPath对应的cell的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) return 100;
    return 44;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, footViewHeight)];
    UIView *lineView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 1)];
    [footView addSubview:lineView1];
    
    UIView *lineView2 = [[UIView alloc] initWithFrame:CGRectMake(0, footViewHeight - 1, [UIScreen mainScreen].bounds.size.width, 1)];
    [footView addSubview:lineView2];
    
    if ([self.currentSkinModel isEqualToString:DaySkinModelValue]) {//日间模式
        footView.backgroundColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1.0];
        lineView1.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0];
        lineView2.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0];
    } else {
        footView.backgroundColor = [UIColor blackColor];
        lineView1.backgroundColor = [UIColor blackColor];
        lineView2.backgroundColor = [UIColor blackColor];
    }
    if (section==2) {
        [lineView2 removeFromSuperview];
    }
    return footView;
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    
    if(indexPath.section == 0) {
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenSizeW, 1)];
        [cell addSubview:lineView];
        CGFloat cellHeight = 100;
        CGFloat margin = 10;
        UIImageView *iconView = [[UIImageView alloc] init];
        iconView.frame =CGRectMake(margin, margin, cellHeight - 2*margin, cellHeight - 2*margin);
        iconView.layer.cornerRadius = iconView.frame.size.width * 0.5;
        iconView.layer.masksToBounds = YES;
        [cell addSubview:iconView];
        UILabel *nameLabel = [[UILabel alloc] init];
        CGFloat nameLabelHeight = 25;
        nameLabel.font = [UIFont systemFontOfSize:24];
        nameLabel.frame = CGRectMake(CGRectGetMaxX(iconView.frame) + 7*margin, iconView.frame.origin.y +iconView.frame.size.height*0.5 - nameLabelHeight/2 , ScreenSizeW - 7*margin - iconView.frame.size.width, nameLabelHeight);
        [cell addSubview:nameLabel];
        [[XJUserInfoManager shareManager]loadFromSandBox];
        if ([XJUserInfoManager shareManager].loginStatus) {
            NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"headerImage"];
            UIImage *image = [UIImage imageWithContentsOfFile:path];
            if (image == nil) {
                image = [UIImage imageNamed:@"defaultUserIcon"];
                [UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
            }
            iconView.image = image;
            nameLabel.text = [XJUserInfoManager shareManager].uname;
        }else {
            iconView.image = [UIImage imageNamed:@"defaultUserIcon"];
            nameLabel.text = @"点此登录";
        }
        
        if ([self.currentSkinModel isEqualToString:DaySkinModelValue]) {//日间模式
            nameLabel.textColor = [UIColor blackColor];

            lineView.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0];
        } else {
            nameLabel.textColor = [UIColor grayColor];
            lineView.backgroundColor = [UIColor blackColor];
        }
      
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"夜间模式";
            if (cell.accessoryView == nil) {
                UISwitch *changeSkinSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 51, 31)];
                self.changeSkinSwitch = changeSkinSwitch;
                [changeSkinSwitch addTarget:self action:@selector(switchDidChange:) forControlEvents:UIControlEventValueChanged];
                cell.accessoryView = changeSkinSwitch;
            }

        }else if (indexPath.row == 1) {
            cell.textLabel.text = @"清除缓存";
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%.1f MB",self.cacheSize];

        }
        
    } else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"我的收藏";
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        } else if(indexPath.row == 1) {
            cell.textLabel.text = @"注销登录";
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        
    }
    
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//夜间模式
        cell.backgroundColor = [UIColor colorWithRed:35/255.0 green:32/255.0 blue:36/255.0 alpha:1.0];
        cell.textLabel.textColor = [UIColor colorWithRed:111/255.0 green:109/255.0 blue:112/255.0 alpha:1.0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        self.changeSkinSwitch.on = YES;
    } else {//日间模式
        cell.backgroundColor =[UIColor whiteColor];
        cell.textLabel.textColor = [UIColor blackColor];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        self.changeSkinSwitch.on = NO;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1 && indexPath.row ==1) {
        [SVProgressHUD show];
        //清除缓存
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            
            NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
            for (NSString *p in files) {
                NSError *error;
                NSString *path = [cachPath stringByAppendingPathComponent:p];
                if ([[NSFileManager defaultManager]fileExistsAtPath:path]) {
                    [[NSFileManager defaultManager]removeItemAtPath:path error:&error];
                }
            }
        });
        
        [SVProgressHUD showSuccessWithStatus:@"缓存清除完毕!"];
        [self performSelector:@selector(dismissShowView) withObject:nil afterDelay:1];
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"0.0MB"];
        
    }else if (indexPath.section == 0 && indexPath.row == 0) {
        if (![XJUserInfoManager shareManager].loginStatus) {
            [self presentViewController:[[LoginViewController alloc] init] animated:YES completion:nil];
        }else {
        [self.navigationController pushViewController:[[EditUserInfoViewController alloc] init] animated:YES];
        }
    }else if (indexPath.section == 2 && indexPath.row == 0) {
        if (![XJUserInfoManager shareManager].loginStatus) {
            [self presentViewController:[[LoginViewController alloc] init] animated:YES completion:nil];
        }else {
            SelectedTableViewController *selecVC = [[SelectedTableViewController alloc]init];
            selecVC.dataSource = [[DBManager shareManager]selecteAllCollect].mutableCopy;
            [self.navigationController pushViewController:selecVC animated:YES];
        }
    }else if (indexPath.section == 2 && indexPath.row == 1) {
        [XJUserInfoManager shareManager].loginStatus = NO;
        [[XJUserInfoManager shareManager]saveUserInfo];
        NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath1] withRowAnimation:(UITableViewRowAnimationFade)];
    }
}

- (void)dismissShowView {
    [SVProgressHUD dismiss];
}

-(void)switchDidChange:(UISwitch *)theSwitch {
    if (theSwitch == self.changeSkinSwitch) {
        if (theSwitch.on == YES) {//切换至夜间模式
            [[NSUserDefaults standardUserDefaults] setObject:NightSkinModelValue forKey:CurrentSkinModelKey];
        } else {
            [[NSUserDefaults standardUserDefaults] setObject:DaySkinModelValue forKey:CurrentSkinModelKey];
        }
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:SkinModelDidChangedNotification object:self];
    } else if (theSwitch == self.imageDownLoadModeSwitch) {//智能无图
        BOOL status = self.imageDownLoadModeSwitch.on;
         //系统偏好设置 将其写入沙盒
        [[NSUserDefaults standardUserDefaults] setObject:@(status) forKey:IsDownLoadNoImageIn3GKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}



/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
